import { defineStore } from 'pinia'

export const usePlayerStore = defineStore('player', {
  state: () => ({
    isPlaying: false,
    currentSong: {
      name: '一程山路',
      artist: '毛不易',
      cover: 'https://img0.baidu.com/it/u=3674450988,2177791649&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500',
      url: '/2.mp3',
    },
    progress: 0, // 0~100
    currentTime: 0, // 当前播放时间（秒）
    duration: 0, // 总时长（秒）
    audio: null,
    isLoading: false, // 音频加载状态
  }),
  actions: {
    play() {
      if (!this.audio) {
        this.isLoading = true
        this.audio = new Audio(this.currentSong.url)
        
        // 音频加载完成
        this.audio.addEventListener('loadedmetadata', () => {
          this.duration = Math.floor(this.audio.duration)
          this.isLoading = false
        })
        
        // 播放结束
        this.audio.addEventListener('ended', () => {
          this.isPlaying = false
          this.currentTime = 0
          this.progress = 0
        })
        
        // 播放进度更新
        this.audio.addEventListener('timeupdate', () => {
          if (this.audio.duration && !isNaN(this.audio.duration)) {
            this.currentTime = Math.floor(this.audio.currentTime)
            this.progress = Math.floor((this.audio.currentTime / this.audio.duration) * 100)
          }
        })
        
        // 错误处理
        this.audio.addEventListener('error', () => {
          this.isLoading = false
          console.error('音频加载失败')
        })
      }
      
      this.audio.play().catch(error => {
        console.error('播放失败:', error)
        this.isPlaying = false
        this.isLoading = false
      })
      this.isPlaying = true
    },
    
    pause() {
      if (this.audio) {
        this.audio.pause()
      }
      this.isPlaying = false
    },
    
    toggle() {
      this.isPlaying ? this.pause() : this.play()
    },
    
    setProgress(val) {
      if (this.audio && this.audio.duration && !isNaN(this.audio.duration)) {
        const newTime = (val / 100) * this.audio.duration
        this.audio.currentTime = newTime
        this.progress = val
        this.currentTime = Math.floor(newTime)
      }
    },
    
    setSong(song) {
      this.currentSong = song
      if (this.audio) {
        this.audio.pause()
        this.audio = null
      }
      this.progress = 0
      this.currentTime = 0
      this.duration = 0
      this.isLoading = false
      this.play()
    }
  }
}) 